package com.estock.platform.task.support;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.estock.common.model.task.Task;


/**
 * @author richard
 *
 */
public class TaskThreadRepository {
	
	private static TaskThreadRepository instance;
	private Map<String, Thread> threadRepo = new HashMap<String, Thread>();
	
	public static TaskThreadRepository getInstance() {
		if (instance == null) {
			instance = new TaskThreadRepository();
		}
		return instance;
	}
	
	public void register(Set<Task> tasks) {
		if (tasks == null) return;
		for (Task task : tasks) {
			register(task);
		}
	}
	
	public void register(Task task) {
		Thread thread = new AutoRunTaskThread(task);
		register(task.getName(), thread);
	}
	
	private void register(final String taskName, final Thread thread) {
		final Thread currentThread = threadRepo.get(taskName);
		if (currentThread == null) {
			threadRepo.put(taskName, thread);
			thread.start();
			return;
		}
		if (currentThread.isAlive()) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					while(currentThread.isAlive()) {
						;
					}
					threadRepo.put(taskName, thread);
					thread.start();
				}
			}).start();
		} else {
			threadRepo.put(taskName, thread);
			thread.start();
		}
	}
	
}
